package com.douya.pangu.application.sys.controller;

import com.douya.common.pojo.vo.CommonResponseVO;
import com.douya.mvc.aop.Cacheable;
import com.douya.pangu.application.basic.service.CoreUserService;
import com.douya.pangu.application.sys.service.UserService;
import com.douya.pangu.application.sys.pojo.vo.LoginUserVO;
import com.douya.pangu.core.api.constant.CoreConsumerConstant;
import com.douya.pangu.core.api.sys.pojo.vo.CoreUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.SendStatus;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * 说明：用户接口
 *
 * @Author hcy
 * @Date 2022/11/10
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/web/sys/user")
public class UserController {

    @Resource
    UserService mUserService;

    @Resource
    CoreUserService coreUserService;

    @Resource
    RocketMQTemplate rocketMqTemplate;


    /**
     * 说明：登录
     *
     * @param loginName 登录名
     * @param password  密码
     * @return 登录用户信息
     */
    @PostMapping("/login")
    public CommonResponseVO<LoginUserVO> login(
            @NotNull(message = "ID不能为空") String loginName,
            @NotNull(message = "ID不能为空") String password
    ) {
        return CommonResponseVO.success(mUserService.login(loginName, password));
    }

    @PostMapping("/test")
    public CommonResponseVO<?> test() {
        long start = System.currentTimeMillis();
        log.info(Thread.currentThread().getName() + "主线程执行开始");
        CountDownLatch countDownLatch = new CountDownLatch(10000);
        for (int i = 0; i < 10000; i++) {
            int finalI = i;
            CompletableFuture.runAsync(() -> {
                testSync(finalI);
                countDownLatch.countDown();
                long count = countDownLatch.getCount();
                log.info("count:" + count);
            });
        }
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info(Thread.currentThread().getName() + "主线程执行完毕,耗时（ms）" + (System.currentTimeMillis() - start));
        return CommonResponseVO.success();
    }

    @PostMapping("/test1")
    public CommonResponseVO<?> test1() {
        long start = System.currentTimeMillis();
        log.info(Thread.currentThread().getName() + "主线程执行开始");
        for (int i = 0; i < 10000; i++) {
            testSync(i);
        }
        log.info(Thread.currentThread().getName() + "主线程执行完毕,耗时（ms）" + (System.currentTimeMillis() - start));
        return CommonResponseVO.success();
    }

    public void testSync(int i) {
//        for (int i = 0; i < 100; i++) {
        // 日志打印当前线程名称
        log.info(Thread.currentThread().getName() + "执行:" + i);
//        }
    }

    /**
     * 说明：注册
     *
     * @param loginName 用户名
     * @param password  用户密码
     */
    @PostMapping("/register")
    public CommonResponseVO<?> register(
            @NotNull String loginName,
            @NotNull String password
    ) {
        mUserService.register(loginName, password);
        return CommonResponseVO.success();
    }

    /**
     * 说明：修改密码
     *
     * @param loginName   用户名
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     */
    @PostMapping("/updatePassword")
    public CommonResponseVO<?> updatePassword(
            @NotNull String loginName,
            @NotNull String oldPassword,
            @NotNull String newPassword
    ) {
        mUserService.updatePassword(loginName, oldPassword, newPassword);
        return CommonResponseVO.success();
    }

    /**
     * 根据ID获取核心用户表
     *
     * @param id ID
     * @return 核心用户表
     */
    @GetMapping(value = "findById")
    @Cacheable(expireTime = 30, timeUnit = TimeUnit.SECONDS)
    public CommonResponseVO<CoreUserVO> findById(@NotNull(message = "ID不能为空") @RequestParam("id") Long id) {
        return CommonResponseVO.success(coreUserService.findById(id));
    }

    @GetMapping(value = "send")
    public void send() {
        DefaultMQProducer producer = rocketMqTemplate.getProducer();
        try {
            SendResult send = producer.send(
                    new Message(CoreConsumerConstant.CoreConsumerTopicConstant.PAN_GU_CORE_TOPIC, "测试消息".getBytes())
            );
            SendStatus sendStatus = send.getSendStatus();
            if (sendStatus == SendStatus.SEND_OK) {
                log.info("发送消息成功");
            } else {
                log.info("发送消息失败");
            }
        } catch (Exception e) {
            log.error("发送消息失败", e);
        }
    }

}
